<template>
  <div class="vote-out">
    <Scroll ref="scroll" :listenScroll="true" @scroll="scrollMove" @pullingUp="pullingUp" @pullingDown="pullingDown">
      <div class="vote">
        <div class="pulling-down" v-text="pullDown.text"></div>
        <div class="top-img">
          <Swipe :autoplay="3000">
            <SwipeItem v-for="(t, i) in bannerArray" :key="i"><img :src="'https://img.sdwsl.net/'+t"></SwipeItem>
          </Swipe>
        </div>
        <div class="vote-info">
          <div class="vote-info-item">
            <div class="vote-info-item-top">参与选手</div>
            <div class="vote-info-item-bottom" v-text="voteUserPage.totalRow"></div>
          </div>
          <div class="vote-info-item">
            <div class="vote-info-item-top">累计投票</div>
            <div class="vote-info-item-bottom" v-text="pollCount"></div>
          </div>
          <div class="vote-info-item">
            <div class="vote-info-item-top">访问量</div>
            <div class="vote-info-item-bottom" v-text="voteVisit"></div>
          </div>
        </div>

        <div class="vote-time">
          <div class="vote-time-icon">
            <Icon name="underway"/>
          </div>
          <div class="vote-time-text" v-text="'投票日期：'+vote.startTime+' 至 '+vote.endTime"></div>
        </div>

        <div class="vote-time">
          <div class="vote-time-icon">
            <Icon name="underway"/>
          </div>
          <div class="vote-time-text">
            活动剩余：{{countDown}}
          </div>
        </div>
        <div style="height: 10px;"></div>

        <div style="text-align: center;">
          <Button type="primary" size="small" class="vote-button" @click="showPrize = true">规则/奖品</Button>
          <Button type="primary" size="small" class="vote-button" @click="showRankScroll">比赛排名</Button>
          <Button type="primary" size="small" class="vote-button" @click="showApplyPopup">我要报名</Button>
        </div>

        <div style="height: 10px;"></div>

        <Search placeholder="请输入选手编号搜索" v-model="searchValue" show-action class="vote-search" style="background-color: #fff;padding-right: 15px;margin-bottom: 8px;">
          <Button slot="action" @click="search" type="primary" size="small" class="vote-search-button">搜索</Button>
        </Search>

        <Tabs @click="handleTabClick" type="card" class="vote-tabs">
          <Tab v-for="item in [{key: 1, title: '人气选手'}, {key: 2, title: '最新参与'}]" :title="item.title" :key="item.key"></Tab>
        </Tabs>

        <div class="waterfalls">
          <ul>
            <template v-for="(item,i) in itemLeft">
              <router-link :to="'/wx/i/votes-'+$route.params.id+'-item-' + item.id + '-l-' + i" tag="li" :data-id="item.applyId">
                <div class="waterfalls-img">
                  <img :src="'https://img.sdwsl.net/'+item.cover+'?imageView2/0/w/260/format/jpg/q/100'">
                </div>
                <div class="waterfalls-title" v-text="item.name"></div>
                <!--<div class="waterfalls-summary">小米公司自创办以来，一直保持高速增长，除手机业务，它独特的生态链模式创造了令人惊讶的成绩456</div>-->
                <div class="waterfalls-btn">
                  <div class="waterfalls-btn-left" v-text="'票数:'+item.poll"></div>
                  <div class="waterfalls-btn-right">
                    <Button type="primary" size="small" class="vote-button">投票</Button>
                  </div>
                </div>
              </router-link>
            </template>
          </ul>
          <ul>
            <template v-for="(item,i) in itemRight">
              <router-link :to="'/wx/i/votes-'+$route.params.id+'-item-' + item.id + '-r-' + i" tag="li" :data-id="item.applyId">
                <div class="waterfalls-img">
                  <img :src="'https://img.sdwsl.net/'+item.cover+'?imageView2/0/w/260/format/jpg/q/100'">
                </div>
                <div class="waterfalls-title" v-text="item.name"></div>
                <!--<div class="waterfalls-summary">小米公司自创办以来，一直保持高速增长，除手机业务，它独特的生态链模式创造了令人惊讶的成绩456</div>-->
                <div class="waterfalls-btn">
                  <div class="waterfalls-btn-left" v-text="'票数:'+item.poll"></div>
                  <div class="waterfalls-btn-right">
                    <Button type="primary" size="small" class="vote-button">投票</Button>
                  </div>
                </div>
              </router-link>
            </template>
          </ul>
        </div>

        <div v-show="moreStatus == 0" style="text-align: center;height: 38px;">
          <div style="height: 30px;line-height: 30px;vertical-align: middle;font-size: 13px;color: #999;">上拉加载更多数据...</div>
        </div>
        <div v-show="moreStatus == 3" style="text-align: center;height: 38px;">
          <div style="height: 30px;line-height: 30px;vertical-align: middle;font-size: 13px;color: #999;">没有更多数据了</div>
        </div>
        <div v-show="moreStatus == 1" style="text-align: center;height: 38px;">
          <Loading type="gradient-circle" color="black" style="display: inline-block;vertical-align: middle;"/>
          <div style="height: 30px;line-height: 30px;display: inline-block;vertical-align: middle;font-size: 13px;color: #999;">数据加载中...</div>
        </div>

      </div>
    </Scroll>

    <div v-show="showGoTop" class="go-top">
      <i class="van-icon van-icon-upgrade" @click="goTop"></i>
    </div>

    <Actionsheet v-model="showPrize" title="规则/奖品" :close-on-click-overlay="false" class="vote-prize">
      <div class="vote-prize-cont">
        <Tabs v-if="showPrize" :active="1">
          <Tab v-for="item in [{title:'活动规则',key:1},{title:'活动奖品',key:2}]" :title="item.title" :key="item.key">
            <!-- 规则 -->
            <template v-if="item.key == 1">
              <div v-html="vote.rule"></div>
            </template>
            <!-- 奖品 -->
            <template v-else>
              <div v-html="vote.prize"></div>
            </template>
          </Tab>
        </Tabs>
      </div>
    </Actionsheet>

    <transition name="slide">
      <router-view @updateVote="updateVote"></router-view>
    </transition>

  </div>

</template>

<script>
  import {Icon, Tab, Tabs, Button, Search, Actionsheet, Panel, Popup, Waterfall, Swipe, SwipeItem, Field, Cell, CellGroup, Loading, Toast} from 'vant'
  import vueWaterfallEasy from 'components/vue-waterfall-easy.vue'
  import Scroll from 'base/scroll/scroll'
  import FormBlock from 'components/form-block'
  import VueQiniuUpload from 'components/vue-qiniu-upload'
  import * as api from '@/api/api'
  import * as Time from '@/js/time'

  export default {
    name: 'index',
    data () {
      return {
        // 投票总数
        pollCount: 0,
        // 访问量
        voteVisit: 0,
        vote: {
          name: '',
          banner: '',
          startTime: '',
          endTime: '',
          rule: '',
          prize: ''
        },
        // 分页信息
        voteUserPage: {
          // 总条数
          totalRow: 0,
          // 当前页数
          pageNumber: 0,
          firstPage: true,
          lastPage: false,
          // 总页数
          totalPage: 1,
          pageSize: 10
        },
        // 倒计时
        countDown: '',
        searchValue: '',
        // 显示规则奖品
        showPrize: false,
        // 显示回到顶部
        showGoTop: false,
        // 封面
        cover: {},
        clientWidth: 0,
        imgWidth: 0,
        // 0=人气选手 1=最新参与
        itemType: 0,
        itemLeft: [],
        itemRight: [],
        waterfalls: {
          leftHeight: 0,
          rightHeight: 0
        },
        // 上拉加载 0=显示上拉加载数据 1=显示正在加载数据 3=显示没有更多数据
        moreStatus: 0,
        pullDown: {
          status: 0, // 0=数据未刷新 1=数据刷新中
          text: '下拉刷新数据'
        }
      }
    },
    methods: {
      // 投票后更新票数显示
      updateVote (lr, index) {
        let itemName = 'itemRight'
        if (lr === 'l') {
          itemName = 'itemLeft'
        }
        console.log(itemName)
        console.log('更新票数')
        console.log(this[itemName])
        this[itemName][index].poll += 1
      },
      search () {
        let applyId = this.searchValue
        if (applyId === '') return
        api.get({
          url: '/vote/user/getForApplyId',
          data: {voteId: this.$route.params.id, applyId: applyId},
          success: data => {
            console.log(data)
            if (data.code === 0) {
              this.$router.push('/wx/i/votes-' + this.$route.params.id + '-item-' + data.data.id)
            } else {
              Toast.fail('没有此选手')
              setTimeout(() => {
                Toast.clear()
              }, 1000)
            }
          }
        })
      },
      goTop () {
        this.$refs.scroll.scrollTo(0, 0, 2000)
      },
      handleTabClick (key) {
        if (this.itemType === key) return
        this.itemType = key
        this.initVoteUsers()
        this.getVoteUserList()
      },
      showApplyPopup () {
        this.$router.push('/wx/i/votes-' + this.$route.params.id + '-apply')
      },
      showRankScroll () {
        this.$router.push('/wx/i/votes-' + this.$route.params.id + '-rank')
      },
      scrollMove (pos, maxScrollY) {
        // console.log(maxScrollY, pos)
        // 下拉刷新
        // 是否立即刷新
        if (this.pullDown.status === 0 && pos.y >= 60) {
          this.pullDown.text = '松开立即刷新'
        } else if (this.pullDown.status === 0 && pos.y > 0) {
          this.pullDown.text = '下拉刷新数据'
        }
        // 上拉加载 start
        if (pos.y < (maxScrollY + -40) && this.moreStatus === 0) {
          // console.log(maxScrollY + -40, pos.y)
          // this.moreStatus = 1
          // this.getVoteUserList()
        }
        // 上拉加载 end
        // 显示回到顶部按钮
        if (pos.y * -1 > document.documentElement.clientHeight) {
          this.showGoTop = true
        } else {
          this.showGoTop = false
        }
      },
      // 上拉加载-加载数据时机
      pullingUp () {
        if (this.moreStatus === 0) {
          this.$refs.scroll.disable()
          this.moreStatus = 1
          this.getVoteUserList()
        }
      },
      // 重置瀑布流数据
      initVoteUsers () {
        // 重置数据
        this.voteUserPage = {
          // 总条数
          totalRow: 0,
          // 当前页数
          pageNumber: 0,
          firstPage: true,
          lastPage: false,
          // 总页数
          totalPage: 1,
          pageSize: 10
        }
        this.itemLeft = []
        this.itemRight = []
        this.waterfalls = {
          leftHeight: 0,
          rightHeight: 0
        }
      },
      // 下拉刷新
      pullingDown () {
        this.pullDown.status = 1
        this.pullDown.text = '数据刷新中...'
        // 重置瀑布流数据
        this.initVoteUsers()
        this.getVoteUserList()
      },
      preload (src, callback) {
        var oImg = new Image()
        oImg.addEventListener('load', (e) => {
          callback(e, oImg)
        })
        oImg.src = src
      },
      // 获取投票信息
      getVote () {
        let voteId = this.$route.params.id
        api.get({
          url: '/admin/vote/getForId',
          data: {voteId: voteId},
          success: data => {
            this.vote = data.data.vote
            this.pollCount = data.data.count
            this.voteVisit = data.data.visit
            document.title = data.data.vote.name
          }
        })
      },
      // 获取投票用户列表
      getVoteUserList () {
        if (this.voteUserPage.pageNumber >= this.voteUserPage.totalPage) {
          this.moreStatus = 3
          this.$refs.scroll.enable()
          return
        }
        let voteId = this.$route.params.id
        let pageNumber = this.voteUserPage.pageNumber + 1
        api.get({
          url: '/vote/user/list',
          data: {voteId: voteId, pageNumber: pageNumber, itemType: this.itemType},
          success: data => {
            this.initVoteUserList(data.data.list)
            let page = data.data
            delete page.list
            this.voteUserPage = page
            this.pullDown.text = '数据加载成功'
          }
        })
      },
      initVoteUserList (items) {
        if (items.length > 0) {
          let item = items.shift()
          this.preload(
            'https://img.sdwsl.net/' + item.cover + '?imageView2/0/w/260/format/jpg/q/100',
            (e, img) => {
              let w1 = img.width
              let h1 = img.height
              let h2 = parseInt(this.imgWidth / w1 * h1)
              if (this.waterfalls.leftHeight <= this.waterfalls.rightHeight) {
                this.itemLeft.push(item)
                this.waterfalls.leftHeight += h2
              } else {
                this.itemRight.push(item)
                this.waterfalls.rightHeight += h2
              }
              this.initVoteUserList(items)
            }
          )
        } else {
          setTimeout(() => {
            // 上拉加载配置恢复
            this.moreStatus = 0
            this.$refs.scroll.finishPullUp()
            // 下拉刷新配置恢复
            this.$refs.scroll.finishPullDown()
            this.pullDown.status = 0

            this.$refs.scroll.refresh()
            this.$refs.scroll.enable()
          }, 100)
        }
      },
      countDownTime () {
        let entTime = this.vote.endTime
        if (entTime === '') {
          return '未开始'
        }

        let countTime = Time.countDown(entTime + ' 00:00:00')
        if (countTime === -1) {
          return '已结束'
        } else {
          return countTime
        }
      },
      init () {
      }
    },
    computed: {
      bannerArray () {
        return this.vote.banner === '' ? [] : this.vote.banner.split(',')
      }
    },
    created () {
      let clientWidth = document.body.clientWidth
      this.clientWidth = clientWidth
      this.imgWidth = (clientWidth - 30) / 2
      // 获取投票信息
      this.getVote()
      this.getVoteUserList()
    },
    mounted () {
      // 倒计时定时器
      setInterval(() => {
        this.countDown = this.countDownTime()
      }, 1000)
    },
    watch: {},
    directives: {
      WaterfallLower: Waterfall('lower')
    },
    components: {Icon, Tab, Tabs, Button, vueWaterfallEasy, Scroll, Search, Actionsheet, Panel, Popup, Waterfall, Swipe, SwipeItem, Field, Cell, CellGroup, FormBlock, Loading, VueQiniuUpload, Toast}
  }
</script>

<style lang="scss">

  .vote-out {
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
  }

  // 下拉刷新
  .pulling-down {
    position: absolute;
    top: -40px;
    left: 0;
    right: 0;
    height: 40px;
    line-height: 40px;
    color: #999999;
    font-size: 13px;
    text-align: center;
  }

  .go-top {
    position: fixed;
    right: 10px;
    bottom: 10px;
    /*background-color: #fff;*/
    /*z-index: 2;*/
    height: 40px;
    width: 40px;
    color: #38f;
    font-size: 30px;
  }

  .vote {
    .top-img {
      /*height: 240px;*/
      min-height: 100px;
      line-height: 0;
      img {
        width: 100%;
        height: auto;
      }
    }
    .vote-info {
      display: flex;
      margin: 10px 0;
      color: #333;
      &-item {
        flex: 1;
        height: 50px;
        display: flex;
        flex-direction: column;
        border-right: 1px solid #e3e2e3;
        &:last-child {
          border-right: 0;
        }
        &-top {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
        }
        &-bottom {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
        }
      }
    }

    &-time {
      display: flex;
      padding-left: 20px;
      height: 36px;
      border-bottom: 1px solid #e3e2e3;
      &-icon {
        width: 40px;
        color: #f44;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
      }
      &-text {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: left;
        font-size: 14px;
      }
    }

    // 瀑布流
    .waterfalls {
      display: flex;
      line-height: 1;
      ul {
        flex: 1;
        padding: 10px 5px;
        &:first-child {
          padding-left: 10px;
        }
        &:last-child {
          padding-right: 10px;
        }
        li {
          margin-bottom: 10px;
          border: 1px solid #ededed;
          box-shadow: 1px 1px 2px 0px #999;
          position: relative;
          overflow: hidden;
          &:before {
            /*content: '编号：'attr(data-id);*/
            content: '\7F16\53F7\FF1A' attr(data-id);
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 25px;
            line-height: 25px;
            background-color: rgba(83, 83, 83, 0.5);
            color: #fff;
            font-size: 13px;
            padding-left: 10px;
          }
          .waterfalls-img {
            line-height: 0;
            img {
              width: 100%;
              height: auto;
            }
          }
          .waterfalls-title {
            padding-left: 10px;
            color: #333;
            font-size: 15px;
            height: 30px;
            line-height: 30px;
            background-color: #e7e7e7;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            overflow: hidden;
          }
          .waterfalls-summary {
            padding: 3px 5px 3px 5px;
            line-height: 1.5;
            font-size: 14px;
            color: #666;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 4;
            overflow: hidden;
          }
          .waterfalls-btn {
            padding: 5px 5px 5px 10px;
            display: flex;
            &-left {
              flex: 1;
              display: flex;
              justify-content: flex-start;
              align-items: center;
              color: red;
              font-size: 13px;
            }
            &-right {
              flex: 1;
              display: flex;
              justify-content: flex-end;
              align-items: center;
            }
          }
        }
      }
    }

  }

  // 活动规则奖品
  .vote-prize {
    height: 100%;
    .van-icon-close {
      color: red !important;
    }
    &-cont {
      .van-tabs__content {
        height: calc(100vh - 88px);
        overflow-y: auto;
        padding: 10px;
        line-height: 1.4;
      }
    }
  }

  .vote-button {
    padding-left: 20px !important;
    padding-right: 20px !important;
  }

  .vote-tabs {
    .van-tabs__nav--card {
      border: 1px solid #38f !important;
    }

    .van-tab {
      color: #38f !important;
      border-right: 1px solid #38f !important;
      &:last-child {
        border-right: 0 !important;
      }
    }

    .van-tab--active {
      color: #fff !important;
      background-color: #38f !important;
    }
  }

  // 复写搜索框样式
  .van-search__input-wrap {
    border-radius: 4px 0px 0px 4px !important;
  }

  .van-search__action {
    width: 60px;
    height: 34px;
    border: 0;
    padding: 0;
    line-height: 0;
  }

  .vote-search-button {
    height: 100% !important;
    border-radius: 0px 4px 4px 0px !important;
    border: 0 !important;
  }

  .slide-enter-active, .slide-leave-active {
    transition: all 0.3s
  }

  .slide-enter, .slide-leave-to {
    transform: translate3d(100%, 0, 0)
  }


</style>
